'use strict'

const Controller = require('egg').Controller

class BlogsController extends Controller {
	async index() {
		const { ctx } = this
		ctx.body = 'hi, egg'
	}

	// 博客查询接口
	async listBlogs() {
		const { ctx, app } = this
		const { page = 1, size = 10 } = ctx.query
		// 处理参数
		const list = await app.mysql.query(
			`select * from blogs where status=1 limit ? offset ?`,
			[size * 1, (page - 1) * size]
		)
		const [count] = await app.mysql.query(
			`select count(id) as count from blogs where status=1 `
		)
		// 返回数据
		ctx.body = {
			code: 0,
			msg: 'succes',
			data: { list, count: count.count }
		}
	}
	// 添加接口
	async addBlogs() {
		const { ctx, app } = this
		// 接收参数
		const {
			title,
			content,
			userId = ctx.state.userInfo.id,
			comments = ''
		} = ctx.request.body
		// 处理
		const insertData = await app.mysql.query(
			`insert into blogs (title, content, userId, comments) values (?,?,?,?)`,
			[title, content, userId, comments]
		)
		// 返回
		if (insertData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: 'success',
				data: { insertId: insertData.insertId }
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '添加失败'
			}
		}
	}
	// 修改接口
	async updateBlogs() {
		const { ctx, app } = this
		// 接收参数
		const { articleId } = ctx.params
		const { title, content, comments = '' } = ctx.request.body
		//
		const updateData = await app.mysql.query(
			`update blogs set title=?, content=?, comments=? where id=?`,
			[title, content, comments, articleId]
		)
		if (updateData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '修改成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '修改失败'
			}
		}
	}
	// 删除接口
	async deleteBlogs() {
		const { ctx, app } = this
		const { deleteId } = ctx.params
		const deleteData = await app.mysql.query(
			`update blogs set status=? where id=?`,
			[2, deleteId]
		)
		if (deleteData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '删除成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '删除失败'
			}
		}
	}
}

module.exports = BlogsController
